<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:xs="http://www.w3.org/2001/XMLSchema"
  xmlns:c="livcos.org/ns/cosmos"
  xmlns=""
  exclude-result-prefixes="c xs">
  
  <xsl:param name="ref" select="'/localhost/system/work'"/>

  <xsl:template match="/">
    <xsl:apply-templates select="document(concat($ref, '.cosmos'))/*"/>
  </xsl:template>
  
  <xsl:template match="c:*">
    <job id="{name(.)}">
      <xsl:apply-templates select="*"/>
    </job>
  </xsl:template>
  
  <xsl:template match="c:request">
    <xsl:variable name="remoteHost" select="interface[@role = 'remote']/@ip"/>
    <xsl:variable name="duration" select="xs:dateTime(../state[last()]/@time) - xs:dateTime(../state[1]/@time)"/>
    <request job="{name(..)}" remote-ip="{$remoteHost}" time="{../state[1]/@time}" duration="{$duration}"
      freeMemory="{../state[last()]/@freeMemory}" totalMemory="{../state[last()]/@totalMemory}">
      <!--xsl:apply-templates select="document(concat('http://www.trynt.com/ip-data-api/v1/?ip=', $remoteHost))/*/*"/-->
      <xsl:copy-of select="url"/>
      <xsl:copy-of select="parameter"/>
      <referer>
        <xsl:value-of select="header/Referer"/>
      </referer>
      <agent>
        <xsl:value-of select="header/User-Agent"/>
      </agent>
    </request>
  </xsl:template>
  
  <xsl:template match="/c:work">
    <jobs>
      <xsl:apply-templates select="*/c:request"/>
    </jobs>
  </xsl:template>
  
  <xsl:template match="IP-Data">
    <host ip="{IP/IP}" name="{IP/Hostname}">
      <xsl:if test="IP/Country != 'UNKOWN'">
        <country name="{IP/Country}" iso="{IP/ISO2}"/>
      </xsl:if>
      <xsl:apply-templates
        select="document(concat('http://www.trynt.com/whois-api/v1/?h=', IP/IP))/*/*"/>
    </host>
  </xsl:template>
  
  <xsl:template match="Whois">
    <owner org="{regrinfo/owner/organization}"/>
    <registrar name="{regyinfo/registrar}"/>
  </xsl:template>
  
</xsl:stylesheet>
